package com.sita.bike.ui.activity.roadtrust;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.nostra13.universalimageloader.utils.L;
import com.sita.bike.R;
import com.sita.bike.event.SharePhotoChangeEvent;
import com.sita.bike.rest.model.LocType;
import com.sita.bike.rest.model.Location;
import com.sita.bike.rest.model.ResourceUploadParams;
import com.sita.bike.rest.model.UploadResourceResponse;
import com.sita.bike.rest.model.response.Reply;
import com.sita.bike.support.Constants;
import com.sita.bike.support.GlobalContext;
import com.sita.bike.ui.view.AudioCircularProgressBar;
import com.sita.bike.utils.AccountUtils;
import com.sita.bike.utils.Bimp;
import com.sita.bike.utils.FileUtils;
import com.sita.bike.utils.ImageItem;
import com.sita.bike.utils.PublicWay;
import com.sita.bike.utils.Res;
import com.sita.bike.utils.RetrofitUtils;
import com.sita.tboard.ActivityBase;
import com.sita.tboard.advertisement.AdvertiseManager;
import com.sita.tboard.roadtrust.event.RtResourceRefreshEvent;
import com.sita.tboard.roadtrust.helper.RtResourceNetworkHelper;
import com.squareup.okhttp.OkHttpClient;

//import org.springframework.http.HttpEntity;
//import org.springframework.http.HttpHeaders;
//import org.springframework.http.HttpMethod;
//import org.springframework.http.MediaType;
//import org.springframework.http.ResponseEntity;
//import org.springframework.http.converter.ByteArrayHttpMessageConverter;
//import org.springframework.http.converter.FormHttpMessageConverter;
//import org.springframework.http.converter.HttpMessageConverter;
//import org.springframework.http.converter.ResourceHttpMessageConverter;
//import org.springframework.http.converter.StringHttpMessageConverter;
//import org.springframework.http.converter.json.GsonHttpMessageConverter;
//import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
//import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter;
//import org.springframework.http.converter.xml.SimpleXmlHttpMessageConverter;
//import org.springframework.http.converter.xml.SourceHttpMessageConverter;
//import org.springframework.util.LinkedMultiValueMap;
//import org.springframework.util.MultiValueMap;
//import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.xml.transform.Source;

import de.greenrobot.event.EventBus;
import retrofit.Callback;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.OkClient;
import retrofit.client.Response;
import retrofit.converter.GsonConverter;
import retrofit.http.Body;
import retrofit.http.Multipart;
import retrofit.http.POST;
import retrofit.http.Part;
import retrofit.mime.MultipartTypedOutput;
import retrofit.mime.TypedFile;
import retrofit.mime.TypedString;


/**
 * 首页面activity
 *
 * @author king
 * @version 2014年10月18日  下午11:48:34
 * @QQ:595163260
 */
public class RoadTrustShareActivity extends ActivityBase implements OnClickListener {
    private static final int TAKE_PICTURE = 0x000001;
    private static final int TAKE_LOCATION = 0x000002;
    public static Bitmap bimap;
    private final String TRAFFIC_NORMAL = "SMOOTH";
    private final String TRAFFIC_SLOW = "SLOW";
    private final String TRAFFIC_CONGESTION = "CONGESTION";
    private final String TRAFFIC_ACCIDENT = "ACCIDENT";
    private GridView noScrollgridview;
    private GridAdapter adapter;
    private View parentView;
    private PopupWindow pic_pop = null;
    private PopupWindow traffic_pop = null;
    private PopupWindow earth_pop = null;
    private LinearLayout pic_ll_popup, traffic_ll_popup, earth_ll_popup;
    private Toolbar mToolbar;
    private String mTrafficStatus = TRAFFIC_CONGESTION;
    private AudioCircularProgressBar mAudioRecorderButton;
    private Button mBtnSend, mBtnCancel;
    private Recorder mRecorder;
    private TextView tv_timer, traffic_tv, earth_state, tv_location;
    private Handler handler;
    private int mContext;
    private EditText edit_content;
    private RelativeLayout traffic_layout, earth_layout, location_layout;
    private String state_content;
    private AMapLocationClient lc;
    private AMapLocation aloc;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Res.init(this);
        bimap = BitmapFactory.decodeResource(
                getResources(),
                R.mipmap.icon_addpic_unfocused);
        parentView = getLayoutInflater().inflate(R.layout.activity_roadtrust_share_upload, null);
        setContentView(parentView);
        tv_timer = (TextView) findViewById(R.id.tv_title_time);
        traffic_tv = (TextView) findViewById(R.id.traffic_tv);
        earth_state = (TextView) findViewById(R.id.earth_state);
        edit_content = (EditText) findViewById(R.id.edit_content);//文字
        tv_location = (TextView) findViewById(R.id.tv_location);
        location_layout = (RelativeLayout) findViewById(R.id.location_layout);
        mAudioRecorderButton = (AudioCircularProgressBar) findViewById(R.id.road_trust_share_record_button);
        mBtnSend = (Button) findViewById(R.id.road_trust_share_send_button);
        mBtnCancel = (Button) findViewById(R.id.road_trust_share_cancel_button);
        mBtnSend.setOnClickListener(this);
        mBtnCancel.setOnClickListener(this);

        lc = GlobalContext.getLocationClient();
        aloc = lc.getLastKnownLocation();

        Init();

    }

    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    public void onEventMainThread(SharePhotoChangeEvent event){
        adapter.notifyDataSetChanged();
    }

    public void initTrafficStatus() {
        state_content = edit_content.getText().toString();
        String trafficstatvs = traffic_tv.getText().toString();
        if (trafficstatvs.equals("顺畅")) {
            mTrafficStatus = TRAFFIC_NORMAL;
        } else if (trafficstatvs.equals("行驶缓慢")) {
            mTrafficStatus = TRAFFIC_SLOW;
        } else if (trafficstatvs.equals("拥堵")) {
            mTrafficStatus = TRAFFIC_CONGESTION;
        } else {
            mTrafficStatus = TRAFFIC_NORMAL;
        }
    }

    @Override
    public void onBackPressed() {
        finish();
    }

    @Override
    public void onClick(View v) {
        if (v == mBtnSend) {
            initTrafficStatus();
            List<File> pics = new ArrayList<>();
            // get all the pictures
            for (int i = 0; i < Bimp.tempSelectBitmap.size(); i++) {
                pics.add(new File(Bimp.tempSelectBitmap.get(i).getImagePath()));
            }

            //play audio
//            MediaManager.playSound(mRecorder.filePath, new MediaPlayer.OnCompletionListener() {
//                @Override
//                public void onCompletion(MediaPlayer mp) {
//                    //
//                }
//            });

            File audio = null;
            if (mRecorder != null && mRecorder.filePath != "") {
                audio = new File(mRecorder.filePath);
            }
            //sendMessage(pics, audio);
            File[] picArray = new File[0];
            if (!pics.isEmpty()){
                picArray = pics.toArray(picArray);
            }
            createRtResource(picArray, audio);
            //if (){
                //sendMessage时，已经finish()了当前activity

            //}

        } else if (v == mBtnCancel) {
            Bimp.tempSelectBitmap.clear();
            EventBus.getDefault().post(new SharePhotoChangeEvent("RoadTrustShareActivity"));
            adapter.notifyDataSetChanged();
            finishListActivity();
            finish();
        }

    }

    /*private void createRtResource(File[] pics, File audio){
        if (TextUtils.isEmpty(state_content) && pics == null){
            Toast.makeText(getApplicationContext(), "请选择图片，声音", Toast.LENGTH_LONG).show();
            return;
        }
        Gson gson = new GsonBuilder().create();
        ResourceUploadParams rp = new ResourceUploadParams();
        rp.mAccountId = AccountUtils.getAccountID();
        rp.mTrafficType = mTrafficStatus;
        rp.mTitle = state_content;
        rp.mCreateDate = String.valueOf(System.currentTimeMillis());
        //定位
        Location loc = new Location();
        loc.latitude = String.valueOf(aloc.getLatitude());
        loc.longitude = String.valueOf(aloc.getLongitude());
        loc.locType = LocType.GCJ02;
        loc.time = String.valueOf(aloc.getTime());
        loc.province = aloc.getProvince();
        loc.city = aloc.getCity();
        rp.mLocation = loc;

        String params = gson.toJson(rp);


        MaterialDialog uploadDialog = new MaterialDialog.
                Builder(this).
                content(R.string.uploading_wait).
                progress(true, 15000).build();
        uploadDialog.show();

        new UploadTask(uploadDialog).execute(params, pics, audio);
    }*/

    /*private class UploadTask extends AsyncTask<Object, Void, Boolean>{
        private MaterialDialog mUploadDialog;
        public UploadTask(MaterialDialog uploadDialog){
            mUploadDialog = uploadDialog;
        }
        @Override
        protected Boolean doInBackground(Object... params) {
            String paramStr = (String)params[0];
            File[] pics = (File[])params[1];
            File audio = (File)params[2];

            List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
            converters.add(new ByteArrayHttpMessageConverter());
            converters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
            converters.add(new ResourceHttpMessageConverter());
            converters.add(new SourceHttpMessageConverter<Source>());
            converters.add(new AllEncompassingFormHttpMessageConverter());
            converters.add(new FormHttpMessageConverter());
            converters.add(new GsonHttpMessageConverter());
            RestTemplate restTemplate = new RestTemplate(converters);

            MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
            map.add("params", paramStr);
            if (pics != null) {
                for (File pic : pics) {
                    map.add("pic", pic);
                }
            }
            if (audio != null){
                map.add("audio", audio);
            }

            HttpHeaders imageHeaders = new HttpHeaders();
            imageHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
            List<MediaType> accepts = new ArrayList<MediaType>();
            accepts.add(MediaType.APPLICATION_JSON);
            imageHeaders.getAcceptCharset().add(Charset.forName("UTF-8"));
            imageHeaders.setAccept(accepts);

            HttpEntity<MultiValueMap<String, Object>> imageEntity = new HttpEntity<MultiValueMap<String, Object>>(map, imageHeaders);

            String uri = Constants.BASE_URI + "/roadtrust/v1/resources/upload";
            try {
                ResponseEntity<String> re = restTemplate.exchange(uri, HttpMethod.POST, imageEntity, String.class);
                mUploadDialog.dismiss();
                return true;
            } catch (Exception e){
                L.e("createRtResource", e.getMessage() == null ? e.getCause() : e.getMessage());
                mUploadDialog.dismiss();
                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean result) {
            Bimp.tempSelectBitmap.clear();
            EventBus.getDefault().post(new SharePhotoChangeEvent("RoadTrustShareActivity"));
            adapter.notifyDataSetChanged();
            finishListActivity();
            if (result) {
                RtResourceNetworkHelper.getInstance().refreshResourceList();
                EventBus.getDefault().post(new RtResourceRefreshEvent(RtResourceRefreshEvent.Mode.REFRESH));
                exit();
            }
        }
    }*/

    private void createRtResource(File[] pics, File audio){
        final MaterialDialog uploadDialog = new MaterialDialog.
                Builder(this).
                content(R.string.uploading_wait).
                progress(true, 5000).
                build();
        uploadDialog.show();
        String BASE_URL = Constants.BASE_URI;
        RequestInterceptor restInterceptor = new RequestInterceptor() {
            @Override
            public void intercept(RequestFacade request) {
                request.addHeader("Accept", Constants.APPLICATION_JSON);
            }
        };

        Gson gson = new GsonBuilder().create();

        final OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
        okHttpClient.setConnectTimeout(60, TimeUnit.SECONDS);
        okHttpClient.setWriteTimeout(120, TimeUnit.SECONDS);

        RestAdapter restAdapter = new RestAdapter.Builder()
                .setLogLevel(RestAdapter.LogLevel.FULL)
                .setEndpoint(BASE_URL)
                .setConverter(new GsonConverter(gson))
                .setRequestInterceptor(restInterceptor)
                .setClient(new OkClient(okHttpClient))
                .build();

        UploadService service = restAdapter.create(UploadService.class);

        ResourceUploadParams rp = new ResourceUploadParams();
        rp.mAccountId = AccountUtils.getAccountID();
        rp.mTrafficType = mTrafficStatus;
        rp.mTitle = state_content;
        rp.mCreateDate = String.valueOf(System.currentTimeMillis());
        //定位
        Location loc = new Location();
        loc.latitude = String.valueOf(aloc.getLatitude());
        loc.longitude = String.valueOf(aloc.getLongitude());
        loc.locType = LocType.GCJ02;
        loc.time = String.valueOf(aloc.getTime());
        loc.province = aloc.getProvince();
        loc.city = aloc.getCity();
        rp.mLocation = loc;
        String paramStr = gson.toJson(rp);


        MultipartTypedOutput multipartTypedOutput = new MultipartTypedOutput();

        TypedString params = new TypedString(paramStr);
        multipartTypedOutput.addPart("params", params);

        if (audio != null) {
            multipartTypedOutput.addPart("audio", new TypedFile("audio/mp3", audio));
        }
        if (pics != null) {
            if (pics.length == 1){
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                String path = pics[0].getAbsolutePath();
                BitmapFactory.decodeFile(path, options);
                int imageHeight = options.outHeight;
                int imageWidth = options.outWidth;

                String intStorageDirectory = getFilesDir().toString() + File.separator + "image";
                String newFile = intStorageDirectory + File.separator + imageWidth + "x" + imageHeight + ".jpg";
                pics[0].renameTo(new File(newFile));
            }
            for (int i = 0; i < pics.length; i++) {
                multipartTypedOutput.addPart("pic", new TypedFile("image/jpg", pics[i]));
            }
        }

        service.upload(multipartTypedOutput, new Callback<UploadResourceResponse>() {
            @Override
            public void success(UploadResourceResponse uploadResourceResponse, Response response) {
                Toast.makeText(GlobalContext.getGlobalContext(), getResources().getText(R.string.upload_ok), Toast.LENGTH_SHORT).show();
                uploadDialog.dismiss();
                RtResourceNetworkHelper.getInstance().refreshResourceList();
                EventBus.getDefault().post(new RtResourceRefreshEvent(RtResourceRefreshEvent.Mode.REFRESH));

                Bimp.tempSelectBitmap.clear();
                EventBus.getDefault().post(new SharePhotoChangeEvent("RoadTrustShareActivity"));
                adapter.notifyDataSetChanged();
                finishListActivity();

                RoadTrustShareActivity.this.finish();
            }

            @Override
            public void failure(RetrofitError error) {
                //Toast.makeText(GlobalContext.getGlobalContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                uploadDialog.dismiss();
                //RetrofitUtils.displayError(RoadTrustShareActivity.this, error);
                L.e("sendMessage()", error);
            }
        });
    }

    private void sendMessage(List<File> pics, File audio) {
//
//        if ((pics == null || pics.size() == 0) && audio == null) {
//            Toast.makeText(getApplicationContext(), "请选择图片，声音", Toast.LENGTH_LONG).show();
//            return;
//        }

        final MaterialDialog uploadDialog = new MaterialDialog.
                Builder(this).
                content(R.string.uploading_wait).
                progress(true, 5000).
                build();
        uploadDialog.show();

        String BASE_URL = Constants.BASE_URI;
        RequestInterceptor restInterceptor = new RequestInterceptor() {
            @Override
            public void intercept(RequestFacade request) {
                request.addHeader("Accept", Constants.APPLICATION_JSON);
            }
        };

        Gson gson = new GsonBuilder().create();

        final OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
        okHttpClient.setConnectTimeout(60, TimeUnit.SECONDS);
        okHttpClient.setWriteTimeout(120, TimeUnit.SECONDS);

        RestAdapter restAdapter = new RestAdapter.Builder()
                .setLogLevel(RestAdapter.LogLevel.FULL)
                .setEndpoint(BASE_URL)
                .setConverter(new GsonConverter(gson))
                .setRequestInterceptor(restInterceptor)
                .setClient(new OkClient(okHttpClient))
                .build();

        UploadService service = restAdapter.create(UploadService.class);

        TypedFile[] picFiles = null;
        if (pics != null && !pics.isEmpty()) {
            picFiles = new TypedFile[pics.size()];
            for (int i = 0; i < pics.size(); i++) {
                TypedFile picFile = new TypedFile("image/jpg", pics.get(i));
                picFiles[i] = picFile;
            }
        }

        TypedFile audioFile = (audio == null) ? null : new TypedFile("audio/mp3", audio);

        ResourceUploadParams rp = new ResourceUploadParams();
        rp.mAccountId = AccountUtils.getAccountID();
        rp.mTrafficType = mTrafficStatus;
        rp.mTitle = state_content;
        rp.mCreateDate = String.valueOf(System.currentTimeMillis());


        //定位

        Location loc = new Location();
        loc.latitude = String.valueOf(aloc.getLatitude());
        loc.longitude = String.valueOf(aloc.getLongitude());
        loc.locType = LocType.GCJ02;
        loc.time = String.valueOf(aloc.getTime());
        loc.province = aloc.getProvince();
        loc.city = aloc.getCity();
        rp.mLocation = loc;

        String rpstr = gson.toJson(rp);

        TypedString params = new TypedString(rpstr); //"{\"accountId\": \"1\",\"trafficType\": \"traffic-type\",\"title\": \"title\",\"location\": {\"longitude\":\"117.280512\",\"latitude\":\"39.154618\",\"locType\":\"GCJ02\",\"time\":\"1446864018768\"},\"createDate\": \"1446864018768\"}");

        MultipartTypedOutput multipartTypedOutput = new MultipartTypedOutput();
        if (picFiles != null) {
            for (int i = 0; i < picFiles.length; i++) {
                multipartTypedOutput.addPart("pic", picFiles[i]);
            }
        }
        multipartTypedOutput.addPart("audio", audioFile);
        multipartTypedOutput.addPart("params", params);

        service.upload(multipartTypedOutput, new Callback<UploadResourceResponse>() {
            @Override
            public void success(UploadResourceResponse uploadResourceResponse, Response response) {
                Toast.makeText(GlobalContext.getGlobalContext(), getResources().getText(R.string.upload_ok), Toast.LENGTH_SHORT).show();
                uploadDialog.dismiss();
                exit();
            }

            @Override
            public void failure(RetrofitError error) {
                //Toast.makeText(GlobalContext.getGlobalContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                uploadDialog.dismiss();
                //RetrofitUtils.displayError(RoadTrustShareActivity.this, error);
                L.e("sendMessage()", error);
            }
        });



        /*service.upload(picFiles, audioFile, params, new Callback<UploadResourceResponse>() {
                    @Override
                    public void success(UploadResourceResponse resourceResponse, Response response) {
                        if (response.getStatus() == 200 && resourceResponse.mErrorCode.equals("0")) {
                            Toast.makeText(getApplicationContext(), getResources().getText(R.string.upload_ok), Toast.LENGTH_LONG).show();
                            uploadDialog.dismiss();
                            exit();
                        } else {
                            Toast.makeText(getApplicationContext(),
                                    getResources().getText(R.string.upload_fail).toString(), Toast.LENGTH_LONG).show();
                            uploadDialog.dismiss();

                        }
                        Log.d("response", response.getReason());
                    }

                    @Override
                    public void failure(RetrofitError error) {
                        uploadDialog.dismiss();
                        RetrofitUtils.displayError(RoadTrustShareActivity.this, error);
                        Log.d("response", error.getMessage());
                    }
                });
            */
    }

    private void exit() {
        this.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public void Init() {

        location_layout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(RoadTrustShareActivity.this, PoiAroundSearchActivity.class);
                Bundle bundle = new Bundle();
                bundle.putDouble("Latitude", aloc.getLatitude());
                bundle.putDouble("Longitude", aloc.getLongitude());
                intent.putExtras(bundle);
                startActivityForResult(intent, TAKE_LOCATION);
            }
        });

        pic_pop = new PopupWindow(RoadTrustShareActivity.this);
        View view = getLayoutInflater().inflate(R.layout.item_popupwindows, null);
        pic_ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);
        pic_pop.setWidth(LayoutParams.MATCH_PARENT);
        pic_pop.setHeight(LayoutParams.WRAP_CONTENT);
        pic_pop.setBackgroundDrawable(new BitmapDrawable());
        pic_pop.setFocusable(true);
        pic_pop.setOutsideTouchable(true);
        pic_pop.setContentView(view);

        RelativeLayout parent = (RelativeLayout) view.findViewById(R.id.parent);
        Button bt1 = (Button) view
                .findViewById(R.id.item_popupwindows_camera);
        Button bt2 = (Button) view
                .findViewById(R.id.item_popupwindows_Photo);
        Button bt3 = (Button) view
                .findViewById(R.id.item_popupwindows_cancel);
        parent.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                pic_pop.dismiss();
                pic_ll_popup.clearAnimation();
            }
        });
        bt1.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                photo();
                pic_pop.dismiss();
                pic_ll_popup.clearAnimation();
            }
        });
        bt2.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                getIntent().putExtra(Constants.BUNDLE_APP_STATE, AdvertiseManager.AppState.IN_CAMERA_PHOTO.name());
                Intent intent = new Intent(RoadTrustShareActivity.this,
                        AlbumActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.activity_translate_in, R.anim.activity_translate_out);//动画效果
                pic_pop.dismiss();
                pic_ll_popup.clearAnimation();
            }
        });
        bt3.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                pic_pop.dismiss();
                pic_ll_popup.clearAnimation();
            }
        });

        // Pictures grid view
        noScrollgridview = (GridView) findViewById(R.id.noScrollgridview);
        noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));

        adapter = new GridAdapter(this);
//        adapter.update();
        noScrollgridview.setAdapter(adapter);
        noScrollgridview.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                if (arg2 == Bimp.tempSelectBitmap.size()) {
                    //点击添加照片的按钮
                    Log.i("RoadTrustShareActivity", "相册GridView点击item事件");
                    pic_ll_popup.startAnimation(AnimationUtils.loadAnimation(RoadTrustShareActivity.this, R.anim.activity_translate_in));
                    pic_pop.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);
                } else {
                    //点击已选择的图片
                    Intent intent = new Intent(RoadTrustShareActivity.this,
                            GalleryActivity.class);
                    intent.putExtra("position", "1");
                    intent.putExtra("ID", arg2);
                    startActivity(intent);
                }
            }
        });


        traffic_pop = new PopupWindow(RoadTrustShareActivity.this);
        View traffic_view = getLayoutInflater().inflate(R.layout.item_popupwindows_traffic, null);
        traffic_ll_popup = (LinearLayout) traffic_view.findViewById(R.id.layout_route_plan_popup);

        traffic_pop.setWidth(LayoutParams.MATCH_PARENT);
        traffic_pop.setHeight(LayoutParams.WRAP_CONTENT);
        traffic_pop.setBackgroundDrawable(new BitmapDrawable());
        traffic_pop.setFocusable(true);
        traffic_pop.setOutsideTouchable(true);
        traffic_pop.setContentView(traffic_view);

        RelativeLayout traffic_parent = (RelativeLayout) traffic_view.findViewById(R.id.route_plan_parent);
        Button traffic_bt1 = (Button) traffic_view.findViewById(R.id.traffic_item_smooth);
        Button traffic_bt2 = (Button) traffic_view.findViewById(R.id.traffic_item_slow);
        Button traffic_bt3 = (Button) traffic_view.findViewById(R.id.traffic_item_congestion);
        Button traffic_bt4 = (Button) traffic_view.findViewById(R.id.traffic_item_cancel);
        traffic_parent.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                traffic_pop.dismiss();
                traffic_ll_popup.clearAnimation();
            }
        });
        traffic_bt1.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                traffic_tv.setText("顺畅");
                traffic_pop.dismiss();
                traffic_ll_popup.clearAnimation();
            }
        });
        traffic_bt2.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                traffic_tv.setText("行驶缓慢");
                traffic_pop.dismiss();
                traffic_ll_popup.clearAnimation();
            }
        });
        traffic_bt3.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                traffic_tv.setText("拥堵");
                traffic_pop.dismiss();
                traffic_ll_popup.clearAnimation();
            }
        });
        traffic_bt4.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                traffic_pop.dismiss();
                traffic_ll_popup.clearAnimation();
            }
        });

        traffic_layout = (RelativeLayout) findViewById(R.id.traffic_layout);
        traffic_layout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                traffic_ll_popup.startAnimation(AnimationUtils.loadAnimation(RoadTrustShareActivity.this, R.anim.activity_translate_in));
                traffic_pop.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);
            }
        });


        earth_pop = new PopupWindow(RoadTrustShareActivity.this);
        View earth_view = getLayoutInflater().inflate(R.layout.item_popupwindows_earth, null);
        earth_ll_popup = (LinearLayout) earth_view.findViewById(R.id.earth_ll_popup);

        earth_pop.setWidth(LayoutParams.MATCH_PARENT);
        earth_pop.setHeight(LayoutParams.WRAP_CONTENT);
        earth_pop.setBackgroundDrawable(new BitmapDrawable());
        earth_pop.setFocusable(true);
        earth_pop.setOutsideTouchable(true);
        earth_pop.setContentView(earth_view);

        RelativeLayout earth_parent = (RelativeLayout) earth_view.findViewById(R.id.earth_parent);
        LinearLayout earth_bt1 = (LinearLayout) earth_view.findViewById(R.id.earth_item_public);
        LinearLayout earth_bt2 = (LinearLayout) earth_view.findViewById(R.id.earth_item_friend);
        LinearLayout earth_bt3 = (LinearLayout) earth_view.findViewById(R.id.earth_item_private);
        Button earth_bt4 = (Button) earth_view.findViewById(R.id.traffic_item_cancel);
        earth_parent.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                earth_pop.dismiss();
                earth_ll_popup.clearAnimation();
            }
        });
        earth_bt1.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                earth_state.setText("公开");
                earth_pop.dismiss();
                earth_ll_popup.clearAnimation();
            }
        });
        earth_bt2.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                earth_state.setText("仅好友可见");
                earth_pop.dismiss();
                earth_ll_popup.clearAnimation();
            }
        });
        earth_bt3.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                earth_state.setText("私密");
                earth_pop.dismiss();
                earth_ll_popup.clearAnimation();
            }
        });
        earth_bt4.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                earth_pop.dismiss();
                earth_ll_popup.clearAnimation();
            }
        });

        earth_layout = (RelativeLayout) findViewById(R.id.earth_layout);
        earth_layout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                earth_ll_popup.startAnimation(AnimationUtils.loadAnimation(RoadTrustShareActivity.this, R.anim.activity_translate_in));
                earth_pop.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);
            }
        });
        // Traffic radio buttons
//		mRadioGroupTrafficStatus = (SegmentedRadioGroup)findViewById(R.id.road_trust_share_traffic_status);
//		mRadioGroupTrafficStatus.setOnCheckedChangeListener(this);

//		mToolbar = (Toolbar) findViewById(R.id.roadtrust_share_toolbar);
//		setupToolbar(mToolbar);

        mAudioRecorderButton.setOnClickListener(this);
        mAudioRecorderButton.setAudioFinishRecorderListener(new AudioCircularProgressBar.AudioFinishRecorderListener() {
            @Override
            public void onFinish(float seconds, String filePath) {
                mRecorder = new Recorder(seconds, filePath);
            }
        });
        mAudioRecorderButton.setAudioTimerListener(new AudioCircularProgressBar.AudioTimerListener() {
            @Override
            public void getTime(int count) {
                mContext = count;

                tv_timer.post(new Runnable() {
                    @Override
                    public void run() {
                        tv_timer.setText("" + mContext + "''");
                    }
                });
            }

            @Override
            public void reset() {
                mContext = 0;

                tv_timer.post(new Runnable() {
                    @Override
                    public void run() {
                        tv_timer.setText("" + mContext + "''");
                    }
                });

            }
        });


//		RoadTrustShareActivity.this.runOnUiThread(new Runnable() {
//			@Override
//			public void run() {
//				mAudioRecorderButton.setAudioTimerListener(new AudioCircularProgressBar.AudioTimerListener() {
//					@Override
//					public void getTime(int count) {
//						tv_timer.setText("" + count);
//					}
//				});
//			}
//		});

    }

    public void photo() {
        getIntent().putExtra(Constants.BUNDLE_APP_STATE, AdvertiseManager.AppState.IN_CAMERA_PHOTO.name());
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(openCameraIntent, TAKE_PICTURE);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_PICTURE:
                if (Bimp.tempSelectBitmap.size() < 9 && resultCode == RESULT_OK) {
                    String fileName = String.valueOf(System.currentTimeMillis());
                    Bitmap bm = (Bitmap) data.getExtras().get("data");
                    fileName = FileUtils.saveBitmap(bm, fileName);
                    ImageItem takePhoto = new ImageItem();
                    takePhoto.setBitmap(bm);
                    takePhoto.setImagePath(fileName);
                    Bimp.tempSelectBitmap.add(takePhoto);
                    EventBus.getDefault().post(new SharePhotoChangeEvent("RoadTrustShareActivity"));
                }
                break;
            case TAKE_LOCATION:
                if (resultCode == 0) {
                    String location = data.getExtras().getString("myLocation", "空");
                    tv_location.setText(location);
                }
                break;
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (edit_content.isFocused()) {
            switch (keyCode) {
                case KeyEvent.KEYCODE_DEL:  //delete key
                    L.i("delete key hit"); //you should see this log in ddms after you hit delete key
                    break;
            }
        }
        return super.onKeyUp(keyCode, event);
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (!this.edit_content.isFocused() && (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_DEL)) {
            finishListActivity();
        }
        Bimp.tempSelectBitmap.clear();
        if (!this.edit_content.isFocused()) {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    public void finishListActivity() {
        for (int i = 0; i < PublicWay.activityList.size() - 1; i++) {
            if (null != PublicWay.activityList.get(i)) {
                PublicWay.activityList.get(i).finish();
            }
        }
    }

    public interface UploadService {

        @Multipart
        @POST("/roadtrust/v1/resources/upload")

            //void upload(@Part("pic") List<TypedFile> pics,
        void upload(@Part("pic") TypedFile[] pic,
                    @Part("audio") TypedFile audio,
                    @Part("params") TypedString string1, Callback<UploadResourceResponse> callback);

        @POST("/roadtrust/v1/resources/upload")
        void upload(@Body MultipartTypedOutput output, Callback<UploadResourceResponse> callback);
    }

    @SuppressLint("HandlerLeak")
    public class GridAdapter extends BaseAdapter {
//        Handler handler = new Handler() {
//            public void handleMessage(Message msg) {
//                switch (msg.what) {
//                    case 1:
//                        adapter.notifyDataSetChanged();
//                        break;
//                }
//                super.handleMessage(msg);
//            }
//        };
        private LayoutInflater inflater;
        private int selectedPosition = -1;
        private boolean shape;

        public GridAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }

        public boolean isShape() {
            return shape;
        }

        public void setShape(boolean shape) {
            this.shape = shape;
        }

        public void update() {
            loading();
        }

        public int getCount() {
            if (Bimp.tempSelectBitmap.size() == 9) {
                return 9;
            }
            return (Bimp.tempSelectBitmap.size() + 1);
        }

        public Object getItem(int arg0) {
            return null;
        }

        public long getItemId(int arg0) {
            return 0;
        }

        public int getSelectedPosition() {
            return selectedPosition;
        }

        public void setSelectedPosition(int position) {
            selectedPosition = position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.item_published_grida,
                        parent, false);
                holder = new ViewHolder();
                holder.image = (ImageView) convertView
                        .findViewById(R.id.item_grida_image);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            if (position == Bimp.tempSelectBitmap.size()) {
                holder.image.setImageBitmap(BitmapFactory.decodeResource(
                        getResources(), R.mipmap.icon_addpic_unfocused));//要换的加号的图片
                if (position == 9) {
                    holder.image.setVisibility(View.GONE);
                }
            } else {
                holder.image.setImageBitmap(Bimp.tempSelectBitmap.get(position).getBitmap());
            }

            return convertView;
        }

        public void loading() {
          new Thread(new Runnable() {
                public void run() {
                    while (true) {
                        if (Bimp.max == Bimp.tempSelectBitmap.size()) {
                            Message message = new Message();
                            message.what = 1;
                            handler.sendMessage(message);
                            break;
                        } else {
                            Bimp.max += 1;
                            Message message = new Message();
                            message.what = 1;
                            handler.sendMessage(message);
                        }
                        Log.d("线程ID",Thread.currentThread().getName());
                        Log.d("线程state",Thread.currentThread().getState().toString());
                    }
                }
            }).start();
        }

        public class ViewHolder {
            public ImageView image;
        }
    }

    class Recorder {
        float time;
        String filePath;

        public Recorder(float time, String filePath) {
            super();
            this.time = time;
            this.filePath = filePath;
        }

        public float getTime() {
            return time;
        }

        public void setTime(float time) {
            this.time = time;
        }

        public String getFilePath() {
            return filePath;
        }

        public void setFilePath(String filePath) {
            this.filePath = filePath;
        }


    }
}

